package es.uc3m.setichat.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import es.uc3m.setichat.R;
import es.uc3m.setichat.db.SaveDataContacts;
import es.uc3m.setichat.format.Conversation;
import es.uc3m.setichat.format.ViewContact;
import es.uc3m.setichat.format.ViewConversations;
import es.uc3m.setichat.service.SeTIChatService;
import es.uc3m.setichat.service.SeTIChatServiceBinder;
import es.uc3m.setichat.xmlparser.XmlCreate;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.TextView;

public class ConversationsActivity extends ListActivity {
	
	ListActivity context;
	BroadcastReceiver mensajeReceiver;
	ViewConversations viewConversations;
	private SeTIChatService mService;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);		
		Log.d("ConversationsActivity", "onCreate");
		setContentView(R.layout.conversations);	
		
		context=this;
		
		try{		
			startService(new Intent(ConversationsActivity.this, SeTIChatService.class));
			bindService(new Intent(ConversationsActivity.this, SeTIChatService.class), mConnection, Context.BIND_AUTO_CREATE);

		}catch(Exception e){
			e.printStackTrace();
		}
		
		TextView contactosTexto = (TextView)findViewById(R.id.AddContact);
		contactosTexto.setOnClickListener(new OnClickListener(){
			
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(ConversationsActivity.this, AddContactsActivity.class);
				startActivity(intent);				
			}			
		});
	}
	
	@Override
	public void onDestroy() {
		Log.d("ConversationsActivity", "onDestroy");
		super.onDestroy();	
//		unregisterReceiver(mensajeReceiver);
		unbindService(mConnection);
	}

	@Override
	protected void onStop() {
		Log.d("ConversationsActivity", "onStop");
		super.onStop();

	}
	
	@Override
	protected void onResume() {
		Log.d("ConversationsActivity", "onResume");
		super.onResume();
		refreshContacts();
	}
	
	private ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName className,	IBinder service) {			
			
			Log.d("ConversationsActivity", "onServiceConnected");
			mService=SeTIChatServiceBinder.getService();		
			refreshContacts();
			
			//Enviar mensaje de tipo 5 (connection) al servidor
			SharedPreferences prefs = getSharedPreferences("SeTIChatSignUpPreferences",Context.MODE_PRIVATE);
			String idSource = prefs.getString("token", " ");
			System.out.println("TOKEN conversationactivity0"+idSource);
	
			try {
				String xmlConnection = XmlCreate.connectionMessage(idSource,"");			
				mService.sendMessage(xmlConnection);
			}catch (Exception e) {
				e.printStackTrace();
			}				
			
			mensajeReceiver = new BroadcastReceiver() {
				@Override
				public void onReceive(Context context, Intent intent) {
					refreshContacts();
				}
			};
			IntentFilter mensajeNuevoFilter = new IntentFilter();
			mensajeNuevoFilter.addAction("es.uc3m.SeTIChat.MENSAJE_RECIBIDO");
			registerReceiver(mensajeReceiver, mensajeNuevoFilter);
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			Log.d("ConversationsActivity", "onServiceDisconnected");

		}
	};
	
	private void refreshContacts(){
		ArrayList <Conversation> datos = new ArrayList <Conversation> ();
		SaveDataContacts usdbh = new SaveDataContacts(this, SaveDataContacts.DBNAME, null, 1);	
		SQLiteDatabase db = usdbh.getWritableDatabase();
		if(db!=null){			
			Cursor cur = db.rawQuery("SELECT * FROM ((SELECT mobile, max(id) id FROM mensajes GROUP BY mobile) a JOIN (SELECT id, mensaje, fecha FROM mensajes) b ON a.id=b.id) ORDER BY id DESC", null);
			
			if(cur.getCount()>0){
				while(cur.moveToNext()){
					Conversation auxiliar = new Conversation();
					
					auxiliar.setMobile(cur.getString(cur.getColumnIndex("mobile")));
					auxiliar.setLastMessage(cur.getString(cur.getColumnIndex("mensaje")));					
					SimpleDateFormat sdf = new SimpleDateFormat ("dd-MM-yyyy, hh:mm:ss");
					Date fecha;
					try {
						fecha = sdf.parse(cur.getString(cur.getColumnIndex("fecha")));
						auxiliar.setLastDate(fecha);
					} catch (ParseException e) {
						e.printStackTrace();
					}
					datos.add(auxiliar);
				}				
			}
			
			else{				
				Intent intent = new Intent(this, AddContactsActivity.class);
				startActivity(intent);
				finish();
			}
			
			cur.close();
			db.close();
		}
		
		viewConversations = new ViewConversations (this, datos);
		this.getListView().setAdapter(viewConversations);
		this.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener(){
			
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				Conversation conversacion = viewConversations.getItem(arg2);
				Intent intent = new Intent(ConversationsActivity.this, ChatActivity.class);
				
				String mobile = conversacion.getMobile();
				System.out.println("Movil desde ConversacionesActivity"+mobile);
				intent.putExtra("mobile", mobile);	
				
				startActivity(intent);				
			}			
		});		
	}
}
